package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.conversion.TypeConversionException;
import org.apache.struts2.util.StrutsTypeConverter;
import com.xyzh05.util.DateUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * This class implements a Struts Type Converter and can be used by struts to convert Date's to Strings
 *
 * @author mraible
 */
public class DateConverter extends StrutsTypeConverter {
	// 支持转换的日期格式
	private static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat("dd/MM/yyyy"),
			new SimpleDateFormat("yyyy-MM-dd"),
			new SimpleDateFormat("yyyy/MM/dd") }; 

	@Override
	public Object convertValue(Map context, Object value, Class toType) {
		//浏览器向服务器提交时，进行String to Date的转换
		if (toType == Date.class) {  
			Date date = null;
			String dateString = null;
			String[] params = (String[])value;
			//获取日期的字符串
			dateString = params[0];
			for (DateFormat format : ACCEPT_DATE_FORMATS) {
				try {
					//遍历日期支持格式，进行转换
					return format.parse(dateString);
				} catch(Exception e) {
					continue;
				}
			}
			return null;
		}
		else if (toType == String.class) {   
			//服务器向浏览器输出时，进行Date to String的类型转换
			Date date = (Date)value;
			//输出的格式是yyyy-MM-dd
			return new SimpleDateFormat("yyyy-MM-dd").format(date);
		}
		return null;
	}
	
    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object convertFromString(Map ctx, String[] value, Class arg2) {
        if (value[0] == null || value[0].trim().equals("")) {
            return null;
        }

        try {
            return DateUtil.convertStringToDate(value[0]);
        } catch (ParseException pe) {
            throw new TypeConversionException(pe.getMessage(), pe);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public String convertToString(Map ctx, Object data) {
        return DateUtil.convertDateToString((Date) data);
    }
} 
